package com.pocketsweet.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.R;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLCustomizationRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.adapter.NewLoverInvitedAdapter;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_lover_invited)
public class LoverInvited extends BaseActivity implements OnRefreshListener,
		OnLoadListener, OnItemClickListener {

	private AutoListView invitedListview = null;
	private NewLoverInvitedAdapter newInvitedAdapter;
	public List<MLCustomizationRecord> customizationRecordList = new ArrayList<MLCustomizationRecord>();
	private LinearLayout linBlank;
	private TextView tvBlankNoLover;
	private TextView tvBlankBg;
	private HeaderLayout header;
	private LoadingDailog loading;
	public static final int MORE_DATA_MAX_COUNT = 10; // 每页10个对象
	private boolean IS_UPDATE_LIST = false; // 是否刷新列表
	public int skipDataCount = 0; // 忽略前N个对象
	public static final int BEGIN_TO_LOADING = -1;// 刚进入时列表为空的状态

	AVQuery<MLCustomizationRecord> querys;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Main.ACTION_NEW_INVITED)) {
				getNewLoverList(AutoListView.REFRESH);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		initView();
		setHeaderFunction();
	}

	private void initView() {
		invitedListview = (AutoListView) findViewById(R.id.newInvitedListview);
		linBlank = (LinearLayout) findViewById(R.id.linBlankNoLove);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		tvBlankNoLover = (TextView) findViewById(R.id.tvBlankNoLover);
		tvBlankBg = (TextView) findViewById(R.id.tvBlankBg);
		newInvitedAdapter = new NewLoverInvitedAdapter(this,
				customizationRecordList);
		invitedListview.setAdapter(newInvitedAdapter);
		invitedListview.setPageSize(MORE_DATA_MAX_COUNT);
		invitedListview.setOnRefreshListener(this);
		invitedListview.setOnLoadListener(this);
		invitedListview.setOnItemClickListener(this);
		newInvitedAdapter.notifyDataSetChanged();
		linBlank.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				getNewLoverList(BEGIN_TO_LOADING);

			}
		});
		getNewLoverList(BEGIN_TO_LOADING);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("情感热线");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				LoverInvited.this.finish();
			}
		});
	}

	private void clear() {
		ShareReferanceUtils unreadCustomazitonCount = new ShareReferanceUtils(
				MLApplication.getContext(), "UnreadCustomaziton_"
						+ UserService.getCurrentUserId());
		unreadCustomazitonCount.setIntValue("count", 0);
	}

	@Override
	public void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Main.ACTION_NEW_INVITED);
		registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	private void getNewLoverList(final int what) {
		invitedListview.setVisibility(View.VISIBLE);
		if (what != BEGIN_TO_LOADING) {
			IS_UPDATE_LIST = true; // 如果不是首次加载数据，则该动作为刷新
		} else {
			invitedListview.setRefreshData(); // 初始化显示loading动态图片
			loading = ToolKits.createLoadingDialog(LoverInvited.this, "提交中..");
			loading.setText("正在获取中");
			loading.show();
		}
		if (customizationRecordList == null
				|| customizationRecordList.size() <= 0 || IS_UPDATE_LIST) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
			querys = new AVQuery<MLCustomizationRecord>("MLCustomizationRecord");
			skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
			if (what != AutoListView.LOAD) {
				skipDataCount = 0; // 刷新时不用忽略前面对象
				customizationRecordList.clear();
				clear();
			}
			querys.setSkip(skipDataCount); // 忽略前N个
			querys.whereEqualTo("status", C.LOVE_CALL_WAITING); // 查找所有等待状态的
			querys.include("sponsor");
			querys.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
			querys.orderByDescending("createdAt");
			int gender = UserService.getCurrentUser().getGender();
			if (gender == 1) {
				querys.whereEqualTo("type", 2);
			} else {
				querys.whereEqualTo("type", 1);
			}
			querys.findInBackground(new FindCallback<MLCustomizationRecord>() {

				@Override
				public void done(List<MLCustomizationRecord> recordList,
						AVException e) {
					if (loading.isShowing()) {
						loading.dismiss();
					}
					if (e == null) {
						if (recordList.size() > 0) {
							AVQuery<AVObject> timeoutRecord = new AVQuery<AVObject>(
									"MLCustomizationRecord");
							for (int i = 0; i < recordList.size(); i++) {
								SimpleDateFormat sDateFormat = new SimpleDateFormat(
										"yyyy-MM-dd hh:mm:ss");
								String curDate = sDateFormat
										.format(new java.util.Date());
								String date = sDateFormat.format(recordList
										.get(i).getCreatedAt());
								try {
									Date d1 = sDateFormat.parse(curDate);
									Date d2 = sDateFormat.parse(date);
									long diff = (d1.getTime() - d2.getTime()) / 1000;// 这样得到秒级别
									if (diff >= 600) {// 10分钟前的删除
										AVAnalytics.onEvent(LoverInvited.this,
												"情感热线（作废数）");
										recordList.remove(i);
										timeoutRecord
												.getInBackground(
														recordList.get(i)
																.getObjectId(),
														new GetCallback<AVObject>() {

															@Override
															public void done(
																	AVObject arg0,
																	AVException arg1) {
																if (arg1 == null) {
																	arg0.deleteInBackground();
																}
															}
														});
									}

								} catch (Exception e1) {
								}
							}
							switch (what) {
							case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
								customizationRecordList = recordList;
								invitedListview.onRefreshComplete();
								break;
							case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
								invitedListview.onLoadComplete();
								customizationRecordList.addAll(recordList);
								break;
							case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
								customizationRecordList = recordList;
								invitedListview.onRefreshComplete();
								break;
							}
							if (customizationRecordList.size() > 0) {
								linBlank.setVisibility(View.GONE);
								invitedListview
										.setResultSize(customizationRecordList
												.size());
								newInvitedAdapter
										.setDatas(customizationRecordList);
								newInvitedAdapter.notifyDataSetChanged();
								IS_UPDATE_LIST = false; // 刷新完毕，设为false
							} else {
								linBlank.setVisibility(View.VISIBLE);
								tvBlankNoLover.setVisibility(View.VISIBLE);
								newInvitedAdapter
										.setDatas(customizationRecordList);
								newInvitedAdapter.notifyDataSetChanged();
								invitedListview.setNoData();
							}
						} else {
							linBlank.setVisibility(View.VISIBLE);
							tvBlankNoLover.setVisibility(View.VISIBLE);
							newInvitedAdapter.setDatas(customizationRecordList);
							newInvitedAdapter.notifyDataSetChanged();
							invitedListview.setNoData();
							if (what != AutoListView.LOAD) {
								invitedListview.setVisibility(View.GONE);
							}

						}
						IS_UPDATE_LIST = false; // 刷新完毕，设为false

					} else {
						linBlank.setVisibility(View.VISIBLE);
						tvBlankBg
								.setBackgroundResource(R.drawable.network_error);
						tvBlankNoLover.setText(getResources().getString(
								R.string.blank_network_error));
						// 已加载完全部，取消loading
						invitedListview.setNoData();
					}
				}

			});
		}
	}

	@Override
	public void onLoad() {
		getNewLoverList(AutoListView.LOAD);

	}

	@Override
	public void onRefresh() {
		getNewLoverList(AutoListView.REFRESH);
		invitedListview.setOnRefreshListener(this);

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		if (position - 1 < 0 || newInvitedAdapter.getCount() <= 0 || position - 1 >= newInvitedAdapter.getCount()) {
			return;
		}
		MLCustomizationRecord mlCuRecordr = (MLCustomizationRecord) newInvitedAdapter
				.getItem(position - 1);
		MLUser mlUser = mlCuRecordr.getSponsor();
		Intent intent = new Intent(LoverInvited.this, Profile.class);
		intent.putExtra("nickname", mlUser.getNickname());
		intent.putExtra("userId", mlUser.getObjectId());
		startActivity(intent);
	}
}